package com.pfzy.utildemo.activity.record.sdk;

import android.content.Context;
import android.media.MediaRecorder;
import android.os.Environment;

import com.pfzy.lib.config.log.MyLog;

import java.io.File;
import java.io.IOException;

import static com.superrtc.ContextUtils.getApplicationContext;

/**
 * MediaRecorder 录音管理
 */
public class AudioManager {
    private static volatile AudioManager instance;
    private MediaRecorder mMediaRecorder;
    private File mSoundPath;

    public static AudioManager getInstance(Context context) {
        if (instance == null) {
            synchronized (AudioManager.class) {
                if (instance == null) {
                    instance = new AudioManager();
                }
            }
        }
        return instance;
    }

    public AudioManager() {
        File cacheFile = getApplicationContext().getExternalCacheDir();
        if (cacheFile != null) {
            String cachePath = cacheFile.getAbsolutePath();
            mSoundPath = new File(cachePath, "sound");
            if (!mSoundPath.exists()) {
                mSoundPath.mkdir();
            }
        }

        mMediaRecorder = new MediaRecorder();
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//输入源通过话筒录音；
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);//输出格式
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//音频编码
        mMediaRecorder.setOutputFile(mSoundPath.getPath());// 设置写出文件；
    }

    public String startRecord() {
        _logd("AudioManager 开始录音 startRecord:" + mMediaRecorder);

        try {
            mMediaRecorder.stop();
            mMediaRecorder.release();
        } catch (Exception e) {
            _loge("停止录音错误： " + e);
        }

        File file = new File(mSoundPath, System.currentTimeMillis() + ".aac");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getPath();
    }

    public void endRecord() {
        _logd("AudioManager startRecord:  一分钟录音结束");
        if (mMediaRecorder != null) {
            try {
                mMediaRecorder.stop();
                mMediaRecorder.release();
            } catch (IllegalStateException e) {
            }
        }
    }

    private void _logd(String msg) {
        MyLog.logd("录音管理器 " + msg);
    }

    private void _loge(String msg) {
        MyLog.loge("录音管理器 " + msg);
    }
}
